package com.dp.mallchat.common.websocket;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.dp.mallchat.common.user.domain.ws.enums.WSReqTypeEnum;
import com.dp.mallchat.common.user.domain.ws.req.WSBaseReq;
import com.dp.mallchat.common.user.service.WebSocketService;
import io.netty.channel.*;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: dupeng
 * @CreateTime: 2024-05-05  16:19
 * @Description: TODO
 */
@Slf4j
@Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private WebSocketService webSocketService;

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    /**
     * 当web客户端连接后，触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        atomicInteger.incrementAndGet();
        log.info("新增连接，当前连接数：{}",atomicInteger.get());
        webSocketService = getService();
    }


    /**
     * 客户端主动下线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        offline(ctx.channel());
    }

    /**
     * 客户端与服务端建立连接
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            log.info("握手成功");
            //非在线用户 记录用户连接
            webSocketService.connect(ctx.channel());
            // 已在线用户认证
            String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
            if (StringUtils.isNotBlank(token)) {
                authorization(ctx.channel(), token);
            }

        } else if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
//                System.out.println("读空闲");
                // 用户下线
                offline(ctx.channel());
            }
        }

    }

    /**
     * 用户身份认证
     *
     * @param channel
     */
    private void authorization(Channel channel, String token) {
        webSocketService.authorization(channel, token);
    }


    /**
     * 断开用户连接
     *
     * @param channel
     */
    private void offline(Channel channel) {
        atomicInteger.getAndDecrement();
        log.info("销毁连接，当前连接数：{}",atomicInteger.get());
        webSocketService.remove(channel);
        channel.close();
    }

    private WebSocketService getService() {
        return SpringUtil.getBean(WebSocketService.class);
    }


    /**
     * 读取客户端发送的消息
     *
     * @param channelHandlerContext
     * @param textWebSocketFrame
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println(text);
        WSBaseReq wsBaseReq = JSONUtil.toBean(text, WSBaseReq.class);
        Integer type = wsBaseReq.getType();
        switch (WSReqTypeEnum.of(type)) {
            case LOGIN:
                // 登录
                System.out.println("请求二维码");
                webSocketService.handleLoginReq(channelHandlerContext.channel());
                break;
            case HEARTBEAT:
                // 心跳检查
                System.out.println("心跳检查");
//                authorization(channelHandlerContext.channel());
                break;
            case AUTHORIZE:
                //登录认证
                System.out.println("扫码登录认证");
                break;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("websocket异常", cause);
    }
}
